package com.base.api.order;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.base.self.entity.SelfCancel;
import com.base.self.entity.SelfOrder;
import com.base.self.mapper.SelfCancelMapper;
import com.base.self.mapper.SelfOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Component
@Transactional
@Slf4j
public class CancelPayRunnable implements Runnable {
    private final SelfCancelMapper selfCancelMapper;

    private final SelfOrderMapper selfOrderMapper;

    public CancelPayRunnable(SelfCancelMapper selfCancelMapper,
                             SelfOrderMapper selfOrderMapper) {
        this.selfCancelMapper = selfCancelMapper;
        this.selfOrderMapper = selfOrderMapper;
    }

    @Override
    public void run() {
        final List<SelfCancel> selfCancelList = selfCancelMapper.selectList(new LambdaQueryWrapper<SelfCancel>()
                .eq(SelfCancel::getIsPerform, 0)
                .le(SelfCancel::getExpirationTime, DateUtil.date())
        );
        //log.warn("订单取消数量：{}", selfCancelList.size());
        selfCancelList.forEach(x -> {
            final SelfOrder selfOrder = selfOrderMapper.selectById(x.getOrderId());
            Optional.ofNullable(selfOrder).ifPresent(s -> {
                s.setStatus(5);
                selfOrderMapper.updateById(s);
                x.setIsPerform(1);
                selfCancelMapper.updateById(x);
            });
        });
    }
}
